package com.yang.controller;

import com.yang.domain.User;
import com.yang.feign.PermissionFeignClient;
import com.yang.rocket.RocketMQProducer;
import com.yang.service.UserService;
import com.yang.utils.JwtUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;


@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionFeignClient permissionFeignClient;

    @Autowired
    private RocketMQProducer rocketMQProducer;

    //用户注册
    @PostMapping("/user/register")
    @GlobalTransactional
    public Result register(@RequestBody User user) {
        try {
            String action = "REGISTER";
            boolean flag = userService.registerUser(user);
            // 注册成功后，获取新用户的ID并绑定默认角色
            if (flag) {
                // 根据用户名查询用户获取用户ID
                User registeredUser = userService.selectUserByUsername(user.getUsername());
                // 调用权限服务绑定默认角色（普通用户）
                permissionFeignClient.bindDefaultRole(registeredUser.getUserId());
                //测试seata
                //int i = 1/0;
                //发送日志到RocketMQ
                rocketMQProducer.sendMessage(registeredUser,action);
                return new Result(Code.REGISTER_SUCCESS, true, "注册成功");
            } else {
                return new Result(Code.REGISTER_FAILURE_GENERAL, false, "注册失败，请稍后重试");
            }
        } catch (IllegalArgumentException e) {
            // 根据错误消息返回对应状态码
            String msg = e.getMessage();
            if (msg.contains("用户名已存在")) {
                return new Result(Code.REGISTER_FAILURE_USERNAME_EXISTS, false, msg);
            } else if (msg.contains("邮箱已被使用")) {
                return new Result(Code.REGISTER_FAILURE_EMAIL_EXISTS, false, msg);
            } else if (msg.contains("手机号已被使用")) {
                return new Result(Code.REGISTER_FAILURE_PHONE_EXISTS, false, msg);
            } else {
                return new Result(Code.REGISTER_FAILURE_INVALID_DATA, false, msg);
            }
        }
    }

    //查询用户信息
    @GetMapping("/user/{userId}")
    @GlobalTransactional
    public Result getUserById(@PathVariable Long userId, HttpServletRequest request) {
        try {
            String action = "QUERY";
            // 从请求属性中获取当前用户ID和角色码（由TokenFilter设置）
            Long currentUserId = (Long) request.getAttribute("userId");
            String roleCode = (String) request.getAttribute("roleCode");

            if (currentUserId == null || roleCode == null) {
                return new Result(Code.GET_USER_FAILURE, null, "权限验证失败");
            }
            // 调用Service层方法，权限控制逻辑在Service层
            User user = userService.getUserByIdWithPermission(userId, currentUserId, roleCode);
            if (user != null) {
                // 发送日志到RocketMQ
                rocketMQProducer.sendMessage(userService.selectUserByUserId(currentUserId),user,action);
                return new Result(Code.GET_USER_SUCCESS, user, "获取用户信息成功");
            } else {
                return new Result(Code.GET_USER_FAILURE, null, "用户不存在");
            }
        } catch (IllegalArgumentException e) {
            //没有权限
            return new Result(Code.GET_USER_FAILURE, null, e.getMessage());
        } catch (Exception e) {
            //其他异常
            System.err.println("获取用户信息失败: " + e.getMessage());
            return new Result(Code.GET_USER_FAILURE, null, "获取用户信息失败");
        }
    }

    //修改用户信息
    @PutMapping("/user/{userId}")
    @GlobalTransactional
    public Result updateUser(@PathVariable Long userId, @RequestBody User user, HttpServletRequest request) {
        try {
            String action = "UPDATE";
            // 参数验证
            if (userId == null || userId <= 0) {
                return new Result(Code.UPDATE_USER_FAILURE, false, "用户ID无效");
            }
            if (user == null) {
                return new Result(Code.UPDATE_USER_FAILURE, false, "用户信息不能为空");
            }
            // 从请求属性中获取当前用户ID和角色码（由TokenFilter设置）
            Long currentUserId = (Long) request.getAttribute("userId");
            String roleCode = (String) request.getAttribute("roleCode");
            if (currentUserId == null || roleCode == null) {
                return new Result(Code.UPDATE_USER_FAILURE, false, "权限验证失败");
            }
            // 调用Service层方法，权限控制逻辑在Service层处理
            boolean flag = userService.updateUserWithPermission(userId, user, currentUserId, roleCode);
            if (flag) {
                // 发送日志到RocketMQ
                rocketMQProducer.sendMessage(userService.selectUserByUserId(currentUserId),userService.selectUserByUserId(userId),action);
                return new Result(Code.UPDATE_USER_SUCCESS, true, "更新用户信息成功");
            } else {
                return new Result(Code.UPDATE_USER_FAILURE, false, "更新用户信息失败");
            }
        } catch (IllegalArgumentException e) {
            //参数验证失败
            return new Result(Code.UPDATE_USER_FAILURE, false, e.getMessage());
        } catch (Exception e) {
            //其他异常
            System.err.println("更新用户信息失败: " + e.getMessage());
            return new Result(Code.UPDATE_USER_FAILURE, false, "更新用户信息失败，请稍后重试");
        }
    }

    //用户登录
    @PostMapping("/user/login")
    @GlobalTransactional
    public Result login(@RequestParam String username, @RequestParam String password) {
        try {
            String action = "LOGIN";
            User user = userService.loginUser(username, password);
            // 获取用户角色码
            String roleCode = null;
            try {
                roleCode = userService.getUserRoleCode(user.getUserId());
            } catch (Exception e) {
                System.err.println("获取用户角色码失败: " + e.getMessage());
                // 如果获取角色码失败，使用默认普通用户角色码
                roleCode = "user";
            }
            // 生成包含角色码的JWT token
//            String token;
//            if (roleCode != null && !roleCode.isEmpty()) {
//                token = JwtUtils.generateTokenWithRole(user.getUsername(), roleCode);
//            } else {
//                token = JwtUtils.generateToken(user.getUsername());
//            }
            String token = JwtUtils.generateTokenWithRole(user.getUsername(), roleCode);
            // 防止密码泄露
            user.setPassword(null);
            // 创建包含token、用户信息和角色码的响应对象
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);
            data.put("roleCode", roleCode);
            // 发送日志到RocketMQ
            rocketMQProducer.sendMessage(user,action);
            return new Result(Code.LOGIN_SUCCESS, data, "登录成功");
        } catch (IllegalArgumentException e) {
            String msg = e.getMessage();
            if (msg.contains("用户名或密码错误")) {
                //用户名或密码错误
                return new Result(Code.LOGIN_FAILURE_INVALID_CREDENTIALS, null, msg);
            } else {
                //服务异常
                return new Result(Code.LOGIN_FAILURE_GENERAL, null, msg);
            }
        } catch (Exception e) {
            //其他异常处理
            System.err.println("用户登录失败: " + e.getMessage());
            return new Result(Code.LOGIN_FAILURE_GENERAL, null, "登录失败，请稍后重试");
        }
    }

    //密码重置
    @PostMapping("/user/reset-password")
    @GlobalTransactional
    public Result resetPassword(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
        try {
            String action = "RESET_PASSWORD";
            // 参数验证
            if (username == null || username.trim().isEmpty()) {
                return new Result(Code.RESET_PASSWORD_FAILURE_INVALID_PARAMS, false, "用户名不能为空");
            }
            if (password == null || password.trim().isEmpty()) {
                return new Result(Code.RESET_PASSWORD_FAILURE_INVALID_PARAMS, false, "新密码不能为空");
            }
            // 从请求属性中获取当前用户信息（由TokenFilter设置）
            Long currentUserId = (Long) request.getAttribute("userId");
            String roleCode = (String) request.getAttribute("roleCode");
            if (currentUserId == null || roleCode == null) {
                return new Result(Code.RESET_PASSWORD_FAILURE, false, "用户身份验证失败");
            }
            // 调用带权限控制的密码重置方法
            boolean flag = userService.resetPasswordWithPermission(username, password, currentUserId, roleCode);
            if (flag) {
                // 发送日志到RocketMQ
                rocketMQProducer.sendMessage(userService.selectUserByUserId(currentUserId),userService.selectUserByUsername(username),action);
                return new Result(Code.RESET_PASSWORD_SUCCESS, true, "重置密码成功");
            } else {
                return new Result(Code.RESET_PASSWORD_FAILURE, false, "重置密码失败");
            }
        } catch (IllegalArgumentException e) {
            //参数不合法
            return new Result(Code.RESET_PASSWORD_FAILURE_INVALID_PARAMS, false, e.getMessage());
        } catch (SecurityException e) {
            //权限验证失败
            return new Result(Code.RESET_PASSWORD_FAILURE, false, e.getMessage());
        } catch (Exception e) {
            //其他异常处理
            System.err.println("重置密码失败: " + e.getMessage());
            return new Result(Code.RESET_PASSWORD_FAILURE, false, "重置密码失败，请稍后重试");
        }
    }

    //分页查询用户列表
    @GetMapping("/users")
    @GlobalTransactional
    public Result getUsersByPage(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size, HttpServletRequest request) {
        try {
            String action = "PAGING_QUERY";
            // 参数验证
            if (page < 1 || size < 1 || size > 100) {
                return new Result(Code.GET_USERS_FAILURE_INVALID_PARAMS, null, "分页参数无效");
            }
            // 从请求属性中获取用户ID和角色码（由TokenFilter设置）
            Long currentUserId = (Long) request.getAttribute("userId");
            String roleCode = (String) request.getAttribute("roleCode");
            if (currentUserId == null || roleCode == null) {
                return new Result(Code.GET_USERS_FAILURE_PERMISSION_DENIED, null, "权限验证失败");
            }
            // 获取分页用户列表
            Map<String, Object> result = userService.getUsersByPage(currentUserId, roleCode, page, size);
            // 发送日志到RocketMQ
            rocketMQProducer.sendMessage(userService.selectUserByUserId(currentUserId),action);
            return new Result(Code.GET_USERS_SUCCESS, result, "获取用户列表成功");
        } catch (Exception e) {
            //其他异常处理
            System.err.println("获取用户列表失败: " + e.getMessage());
            return new Result(Code.GET_USERS_FAILURE, null, "获取用户列表失败");
        }
    }

    // 将用户升级为管理员（仅超管可调用）
    @PostMapping("/user/upgradeToAdmin/{userId}")
    @GlobalTransactional
    public Result upgradeToAdmin(@PathVariable Long userId, HttpServletRequest request) {
        try {
            String action = "UPGRADE_TO_ADMIN";
            // 参数验证
            if (userId == null || userId <= 0) {
                return new Result(Code.UPDATE_USER_FAILURE, false, "用户ID无效");
            }
            // 从请求属性中获取当前用户ID和角色码（由TokenFilter设置）
            Long currentUserId = (Long) request.getAttribute("userId");
            String roleCode = (String) request.getAttribute("roleCode");

            if (currentUserId == null || roleCode == null) {
                return new Result(Code.UPDATE_USER_FAILURE, false, "权限验证失败");
            }
            // 调用Service层方法
            boolean flag = userService.upgradeToAdmin(userId, currentUserId, roleCode);
            if (flag) {
                // 发送日志到RocketMQ
                rocketMQProducer.sendMessage(userService.selectUserByUserId(currentUserId),userService.selectUserByUserId(userId),action);
                return new Result(Code.UPDATE_USER_SUCCESS, true, "用户升级为管理员成功");
            } else {
                return new Result(Code.UPDATE_USER_FAILURE, false, "用户升级为管理员失败");
            }
        } catch (SecurityException | IllegalArgumentException e) {
            return new Result(Code.UPDATE_USER_FAILURE, false, e.getMessage());
        } catch (Exception e) {
//            e.printStackTrace();
            //其他异常处理
            System.err.println("升级用户为管理员失败: " + e.getMessage());
            return new Result(Code.UPDATE_USER_FAILURE, false, "升级用户为管理员失败，请稍后重试");
        }
    }

    // 将管理员降级为普通用户（仅超管可调用）
    @PostMapping("/user/downgradeToUser/{userId}")
    @GlobalTransactional
    public Result downgradeToUser(@PathVariable Long userId, HttpServletRequest request) {
        try {
            String action = "DOWNGRADE_TO_USER";
            // 参数验证
            if (userId == null || userId <= 0) {
                return new Result(Code.UPDATE_USER_FAILURE, false, "用户ID无效");
            }
            // 从请求属性中获取当前用户ID和角色码（由TokenFilter设置）
            Long currentUserId = (Long) request.getAttribute("userId");
            String roleCode = (String) request.getAttribute("roleCode");

            if (currentUserId == null || roleCode == null) {
                return new Result(Code.UPDATE_USER_FAILURE, false, "权限验证失败");
            }
            // 调用Service层方法
            boolean flag = userService.downgradeToUser(userId, currentUserId, roleCode);
            if (flag) {
                // 发送日志到RocketMQ
                rocketMQProducer.sendMessage(userService.selectUserByUserId(currentUserId),userService.selectUserByUserId(userId),action);
                return new Result(Code.UPDATE_USER_SUCCESS, true, "管理员降级为普通用户成功");
            } else {
                return new Result(Code.UPDATE_USER_FAILURE, false, "管理员降级为普通用户失败");
            }
        } catch (SecurityException | IllegalArgumentException e) {
            //处理service层抛出的异常
            return new Result(Code.UPDATE_USER_FAILURE, false, e.getMessage());
        } catch (Exception e) {
            //处理其他异常
            System.err.println("降级管理员为普通用户失败: " + e.getMessage());
            return new Result(Code.UPDATE_USER_FAILURE, false, "降级管理员为普通用户失败，请稍后重试");
        }
    }
}
